<template>
  <div>
    <van-nav-bar title="登录" left-arrow @click-left="onClickLeft" />
    <van-form @submit="onSubmit">
      <van-field
        v-model="loginname"
        label="手机号"
        placeholder="请输入手机号"
        :rules="[
          { required: true, message: '请填写手机号' },
          { pattern: /^1[3-9][0-9]{9}$/, message: '手机号不合法' }
        ]"
      />
      <van-field
        v-model="password"
        type="password"
        label="密码"
        placeholder="请输入密码"
        autocomplete
        :rules="[
          { required: true, message: '请填写密码' },
          {
            pattern: /^\w{6,16}$/,
            message: '密码必须是6-16位'
          }
        ]"
      />
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          登 录
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { login } from '@/api/user'
import { showSuccessToast, showFailToast } from 'vant'

const router = useRouter()
const store = useUserStore()

const loginname = ref('17704051019')
const password = ref('123456')

const onClickLeft = () => {
  router.back()
}

// 提交
const onSubmit = async () => {
  const res = await login({
    loginname: loginname.value,
    password: password.value
  })

  if (res.code === 200) {
    // 把token存储到仓库中
    store.setToken(res.data.token)

    // 提示
    showSuccessToast({
      duration: 500,
      message: res.message,
      onClose: () => {
        // 跳转到首页
        router.push('/')
      }
    })
  } else {
    showFailToast(res.message)
  }
}
</script>
